const Core = require('@alicloud/pop-core');
const readline = require('readline');
require('dotenv').config();

const client = new Core({
    accessKeyId: process.env.ALIYUN_IHEALTHIFY_ACCESS_KEY_ID,
    accessKeySecret: process.env.ALIYUN_IHEALTHIFY_ACCESS_KEY_SECRET,
    endpoint: 'https://alidns.aliyuncs.com',
    apiVersion: '2015-01-09'
});

// 获取所有DNS记录（含分页处理）
async function listAllDnsRecords() {
    const params = {
        DomainName: 'smartbiome.cn',
        PageNumber: 1,
        PageSize: 100
    };

    try {
        let allRecords = [];
        let result = await client.request('DescribeDomainRecords', params);
        allRecords = result.DomainRecords.Record;

        const totalPages = Math.ceil(result.DomainRecords.TotalCount / params.PageSize);
        for (let page = 2; page <= totalPages; page++) {
            params.PageNumber = page;
            const response = await client.request('DescribeDomainRecords', params);
            allRecords = allRecords.concat(response.DomainRecords.Record);
        }
        return allRecords;
    } catch (error) {
        console.error('查询DNS记录失败:', error);
        throw error;
    }
}

// 批量删除记录
async function batchDeleteRecords(recordIds) {
    try {
        for (const recordId of recordIds) {
            const result = await client.request('DeleteDomainRecord', {
                RecordId: recordId
            });
            console.log(`✅ 已删除记录 [ID: ${recordId}]`);
        }
    } catch (error) {
        console.error('批量删除失败:', error.message);
        throw error;
    }
}

// 获取用户选择
async function getUserSelection(records) {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    while (true) {
        try {
            const answer = await new Promise(resolve => {
                rl.question(
                    `请选择要删除的记录（输入数字序号，多个用逗号分隔，如：1,3,5）: `,
                    resolve
                );
            });

            const selections = answer.split(',')
                .map(s => s.trim())
                .filter(s => s !== '');

            const validIndexes = selections
                .map(Number)
                .filter(n => !isNaN(n) && n > 0 && n <= records.length)
                .map(n => n - 1);

            if (validIndexes.length === 0) {
                console.log('⚠️ 无效的选择，请重新输入');
                continue;
            }

            const selectedRecords = validIndexes.map(i => records[i]);
            console.log('\n您选择删除的记录：');
            selectedRecords.forEach((r, i) => {
                console.log(`${i + 1}. [${r.RR}] ${r.Type} -> ${r.Value} (ID: ${r.RecordId})`);
            });

            const confirm = await new Promise(resolve => {
                rl.question('确认删除这些记录？(Y/N): ', resolve);
            });

            if (confirm.trim().toUpperCase() === 'Y') {
                await batchDeleteRecords(selectedRecords.map(r => r.RecordId));
                break;
            }
        } finally {
            rl.close();
        }
    }
}

// 主程序
async function main() {
    try {
        console.log('正在查询DNS记录...');
        const records = await listAllDnsRecords();

        if (records.length === 0) {
            console.log('🔍 未找到任何DNS记录');
            return;
        }

        console.log('\n当前DNS记录列表:');
        records.forEach((r, i) => {
            console.log(`${i + 1}. [${r.RR}] ${r.Type} -> ${r.Value} (ID: ${r.RecordId})`);
        });

        await getUserSelection(records);
        console.log('\n操作完成');
    } catch (error) {
        console.error('\n⚠️ 发生错误:', error.message);
    }
}

main();
